//
//  ViewController.m
//  tmp2TableView
//
//  Created by hh on 15/11/30.
//  Copyright © 2015年 hh. All rights reserved.
//

#import "ViewController.h"
#import "EditViewController.h"

@interface ViewController () <EditProtocol>
{
    NSMutableArray *names;
    NSMutableArray *tels;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.title = @"电话薄";
    self.tableView.allowsSelectionDuringEditing = YES;
    names = @[
              @"张三",@"李四",@"王五"
              ].mutableCopy;
    tels = @[
             @"13334567890",
             @"13412345678",
             @"18665432879"
             ].mutableCopy;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(onEdit:)];
}

- (void)onEdit:(UIBarButtonItem *)sender
{
    [self.tableView setEditing:!self.tableView.editing animated:YES];
    sender.title = self.tableView.editing ? @"完成" : @"编辑";
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return tableView.isEditing ? names.count + 1 : names.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    if (indexPath.row < names.count) {
        cell.textLabel.text = names[indexPath.row];
        cell.detailTextLabel.text = tels[indexPath.row];
    }
    return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return indexPath.row == names.count ? UITableViewCellEditingStyleInsert : UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    EditViewController *con = [[EditViewController alloc] initWithStyle:UITableViewStyleGrouped];
    if (indexPath.row < names.count) {
        con.name = names[indexPath.row];
        con.tel = tels[indexPath.row];
    }else{
        [names addObject:@""];
        [tels addObject:@""];
    }
    con.delegate = self;
    [self.navigationController pushViewController:con animated:YES];
    if (tableView.isEditing) {
        [tableView setEditing:NO animated:YES];
    }

}

- (void)editFinishedWithName:(NSString *)name tel:(NSString *)tel
{
    NSIndexPath *indexPath = self.tableView.indexPathForSelectedRow;
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    names[indexPath.row] = name;
    tels[indexPath.row] = tel;
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
